package cn.wolfcode.web.modules.custlinkman.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.wolfcode.web.modules.log.LogModules;

import cn.wolfcode.web.modules.custlinkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.custlinkman.service.ITbCustLinkmanService;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author haiyang
 * @since 2022-10-09
 */
@Controller
@RequestMapping("custlinkman")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;

    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbCustLinkman";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("cust/custlinkman/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('cust:custlinkman:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> custList = customerService.list();
        mv.addObject("custList",custList);
        mv.setViewName("cust/custlinkman/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('cust:custlinkman:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        List<TbCustomer> custList = customerService.list();

        mv.addObject("custList",custList);
        mv.setViewName("cust/custlinkman/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('cust:custlinkman:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName, String custId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page = entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId)
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getLinkman,parameterName)//按联系人名字模糊查询
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getInputUser,parameterName)//按录入人模糊查询
                .page(page);

        List<TbCustLinkman> records = page.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(obj -> {
                TbCustomer customer = customerService.getById(obj.getCustId());
                if (Objects.nonNull(customer)) {

                    obj.setCustomerName(customer.getCustomerName());
                }
            });
        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('cust:custlinkman:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustLinkman entity ,HttpServletRequest request) {

        entity.setInputTime(LocalDateTime.now());

        SysUser loginUser = (SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUser(loginUser.getUserId());//录入人
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('cust:custlinkman:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {

        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('cust:custlinkman:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @RequestMapping("export")
    @SysLog(value = LogModules.EXPORT, module = LogModule)
    public void export(String parameterName, String custId, HttpServletResponse response) {
        List<TbCustLinkman> list = entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId)
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getLinkman, parameterName)//按联系人名字模糊查询
                .or()
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getInputUser, parameterName).list();//按录入人模糊查询
        ExportParams exportParams = new ExportParams();
        //样式、字节码、内容
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbCustLinkman.class, list);
        try {
            PoiExportHelper.exportExcel(response, "联系人管理", workbook);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("listByCustomerId")
    public ResponseEntity listByCustomerId(String custId) {
        if (StringUtils.isEmpty(custId)) {
            return ResponseEntity.ok(ApiModel.ok());
        }
        List<TbCustLinkman> list = entityService.lambdaQuery()
                .eq(TbCustLinkman::getCustId, custId).list();
        return ResponseEntity.ok(ApiModel.data(list));
    }
}
